/*
 *@brief array operate functions
 */

#include "array_op.h"

/*{{{ ksort*/
zend_bool ksort(HashTable * ht)
{
	zval *array;
	//long sort_type = 0;//SORT_REGULAR
	HashTable *target_hash;
	target_hash = ht;
	//set_compare_func(sort_type TSRMLS_CC);
	if (zend_hash_sort(target_hash, zend_qsort, array_key_compare, 0 TSRMLS_CC) == FAILURE) {
		return FAILURE;
	}
	return SUCCESS;
}
/*}}}*/

/*{{{ static int array_key_compare*/
static int array_key_compare(const void *a, const void *b TSRMLS_DC)
{
	Bucket *f;
	Bucket *s;
	zval result;
	zval first;
	zval second;
 
	f = *((Bucket **) a);
	s = *((Bucket **) b);

	if (f->nKeyLength == 0) {
		Z_TYPE(first) = IS_LONG;
		Z_LVAL(first) = f->h;
	} else {
		Z_TYPE(first) = IS_STRING;
		Z_STRVAL(first) = f->arKey;
		Z_STRLEN(first) = f->nKeyLength-1;
	}

	if (s->nKeyLength == 0) {
		Z_TYPE(second) = IS_LONG;
		Z_LVAL(second) = s->h;
	} else {
		Z_TYPE(second) = IS_STRING;
		Z_STRVAL(second) = s->arKey;
		Z_STRLEN(second) = s->nKeyLength-1;
	}

	if (compare_function(&result, &first, &second TSRMLS_CC) == FAILURE) {
		return 0;
	}

	if (Z_TYPE(result) == IS_DOUBLE) {
		if (Z_DVAL(result) < 0) {
			return -1;
		} else if (Z_DVAL(result) > 0) {
			return 1;
		} else {
			return 0;
		}
	}

	convert_to_long(&result);

	if (Z_LVAL(result) < 0) {
		return -1;
	} else if (Z_LVAL(result) > 0) {
		return 1;
	} 

	return 0;
}
/*}}}*/

/*
 *   Local variables:
 *   tab-width: 4
 *   c-basic-offset: 4
 *   End:
 *   vim600: noet sw=4 ts=4 fdm=marker
 *   vim<600: noet sw=4 ts=4
 */

